package cn.shengongying.admin.controller;

import cn.shengongying.bean.DataTablePageResult;
import cn.shengongying.dubbo.modal.Feedback;
import cn.shengongying.dubbo.service.IFeedbackService;
import cn.shengongying.model.Customer;
import cn.shengongying.service.ICustomerService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * author: RXK
 * date: 2022/2/10 星期四
 * desc:
 */
@Controller
@RequestMapping("/sys/feedback")
public class FeedBackController extends BaseController {

    @DubboReference(version = IFeedbackService.version)
    private IFeedbackService feedbackService;

    private final ICustomerService customerService;

    public FeedBackController(ICustomerService customerService) {
        this.customerService = customerService;
    }


    @RequestMapping("/index")
    public String index() {
        return "/feedback/index";
    }


    @ResponseBody
    @RequestMapping("/list")
    public DataTablePageResult<List<Feedback>> list(@RequestBody DataTablePageResult result) {
        List<Feedback> feedbacks = feedbackService.listAndPage(result.getStart(), result.getLength());

        Set<Long> userIds = feedbacks.stream()
                .map(Feedback::getUserId)
                .collect(Collectors.toSet());

        if (CollectionUtils.isNotEmpty(userIds)) {
            List<Customer> list = customerService.listByIds(userIds);
            feedbacks.forEach(feedback -> {
                list.stream()
                        .filter(customer -> customer.getId()
                                .compareTo(feedback.getUserId()) == 0)
                        .findFirst()
                        .ifPresent(customer -> {
                            feedback.setUserName(customer.getNickName());
                        });
            });
        }
        result.setData(feedbacks);
        long count = feedbackService.count();
        result.setRecordsTotal(count);
        return result;
    }


}
